package org.metasketch.ham.model.fileloading;

import java.io.FileReader;
import java.io.FileWriter;

import org.metasketch.ham.model.HAMModel;
import org.metasketch.ham.model.HumanActivity;
import org.metasketch.ham.model.HumanActivityElement;
import org.metasketch.ham.model.HumanActivityGroup;
import org.metasketch.ham.model.HumanActivityParticipationRelationLink;
import org.metasketch.ham.model.HumanActivityRelationLink;
import org.metasketch.ham.model.HumanOrganizationUnit;
import org.metasketch.ham.model.HumanParticipationElement;
import org.metasketch.ham.model.HumanParticipationGroup;
import org.metasketch.ham.model.HumanParticipationRelationLink;
import org.metasketch.ham.model.HumanParticipationUnit;
import org.metasketch.model.BaseModel;

import com.thoughtworks.xstream.XStream;

public class HAMModelFileHandler {

	private static XStream geXStream() {

		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);

		xstream.processAnnotations(HumanActivityElement.class);
		xstream.processAnnotations(HumanActivity.class);
		xstream.processAnnotations(HumanActivityGroup.class);
		xstream.processAnnotations(HumanActivityRelationLink.class);

		xstream.processAnnotations(HumanParticipationElement.class);
		xstream.processAnnotations(HumanParticipationUnit.class);
		xstream.processAnnotations(HumanParticipationGroup.class);
		xstream.processAnnotations(HumanParticipationRelationLink.class);

		xstream.processAnnotations(HumanOrganizationUnit.class);
		xstream.processAnnotations(HumanActivityParticipationRelationLink.class);

		xstream.processAnnotations(HAMModel.class);

		return xstream;
	}

	public static HAMModel read(String path) throws Throwable {
		try {
			XStream xstream = geXStream();

			FileReader reader = new FileReader(path + "\\\\ham-model.xmi");
			HAMModel model = (HAMModel) xstream.fromXML(reader);
			reader.close();

			model.compileIndex();

			return model;

		} catch (Throwable t) {
			t.printStackTrace();
		}

		return new HAMModel();

	}

	public static void write(BaseModel baseModel, String path) throws Throwable {

		XStream xstream = geXStream();

		FileWriter writer = new FileWriter(path + "\\\\ham-model.xmi");
		xstream.toXML(baseModel, writer);
		writer.close();

	}

}
